package com.lang.generator.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.lang.global.ret.Ret;
import cn.lang.global.ret.RetBaseCode;
import com.lang.generator.domain.entity.TableStructure;
import com.lang.generator.domain.vo.SqlParserVo;
import com.lang.generator.service.SqlParserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;

/**
 * sql解析器控制器
 *
 * @author zhangren
 * @date 2022/12/13
 */
@Api(tags = "SQL解析")
@Slf4j
@RequestMapping("/sqlParser")
@RestController
public class SqlParserController {

    @Resource
    private SqlParserService sqlParserService;

    @ApiOperation("解析文件")
    @PostMapping("/file")
    public Ret<List<TableStructure>> sqlParserFile(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            String content = IoUtil.read(inputStream, Charset.defaultCharset());
            List<TableStructure> tableStructures = sqlParserService.sqlParser(content);
            if (CollectionUtil.isEmpty(tableStructures)){
                return Ret.error("sql解析异常");
            }
            return Ret.success(tableStructures);
        } catch (IOException e) {
            log.error("文件读取异常",e);
            return Ret.error(RetBaseCode.SYS_ERROR);
        }
    }

    @ApiOperation("解析文本")
    @PostMapping("/text")
    public Ret<List<TableStructure>> sqlParser(@RequestBody SqlParserVo sqlParserVo) {
        List<TableStructure> tableStructures = sqlParserService.sqlParser(sqlParserVo.getSql());
        if (CollectionUtil.isEmpty(tableStructures)){
            return Ret.error("sql解析异常");
        }
        return Ret.success(tableStructures);
    }
}
